# coding:utf-8
from flask import Flask, render_template
from app.models.base import db
from flask_login import LoginManager
from flask_mail import Mail
from flask_caching import Cache
from app.libs.limit import Limit


login_manager = LoginManager()
mail = Mail()
cache = Cache()
limit = Limit()


# 初始化app
def create_app():
    # 实例化核心app
    app = Flask(__name__)
    app.config.from_object('app.secure')
    app.config.from_object('app.setting')
    # init blueprint
    register_blueprint(app)

    # init SQLAlchemy object
    db.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)
    cache.init_app(app, config={"CACHE_TYPE": "redis",
                                "CACHE_REDIS_HOST": "39.105.148.3"})

    login_manager.login_view = 'web.login' # 检测到未登录时返回的页面
    login_manager.login_message = '登陆或注册' # 闪现的错误提示
    db.create_all(app=app)

    # 全局异常404处理.
    @app.errorhandler(404)
    def not_fand(e):
        return render_template('404.html')

    return app


# 注册蓝图
def register_blueprint(app):
    from app.web.book import web
    app.register_blueprint(web)